package com.christina.engine.execution.impl;

import com.christina.engine.execution.AbstractServiceExecutor;
import com.christina.engine.execution.model.ExecutionRequest;
import com.christina.engine.execution.model.ExecutionResult;
import com.christina.service.domain.travel.TravelDomainService;
import com.christina.service.domain.travel.model.TravelPlanRequest;
import com.christina.service.domain.travel.model.TravelPlanResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 出行服务执行器
 * 负责执行出行规划相关的业务逻辑
 * 
 * @author Christina
 */
@Slf4j
@Component
public class TravelServiceExecutor extends AbstractServiceExecutor {
    
    private final TravelDomainService travelDomainService;
    
    public TravelServiceExecutor(TravelDomainService travelDomainService) {
        super("TravelServiceExecutor", new String[]{"TRAVEL", "TRIP_PLANNING"}, 200);
        this.travelDomainService = travelDomainService;
    }
    
    @Override
    protected ExecutionResult doExecute(ExecutionRequest request) {
        log.debug("Executing travel service for request: {}", request.getRequestId());
        
        try {
            // 验证参数
            validateTravelParameters(request);
            
            // 构建出行规划请求
            TravelPlanRequest travelRequest = buildTravelPlanRequest(request);
            
            // 调用出行领域服务
            TravelPlanResult travelResult = travelDomainService.planTravel(travelRequest);
            
            // 构建执行结果
            return ExecutionResult.success(Map.of(
                    "planId", travelResult.getPlanId(),
                    "routes", travelResult.getRecommendedRoutes(),
                    "totalCost", travelResult.getBestRoute() != null ? travelResult.getBestRoute().getTotalCost() : 0.0,
                    "totalDuration", travelResult.getBestRoute() != null ? travelResult.getBestRoute().getTotalDuration() : 0,
                    "recommendations", travelResult.getSuggestions()
            ), getName());
                    
        } catch (Exception e) {
            log.error("Error executing travel service", e);
            return ExecutionResult.failure("Failed to process travel request: " + e.getMessage(), e, getName());
        }
    }
    
    /**
     * 验证出行参数
     * 
     * @param request 执行请求
     */
    private void validateTravelParameters(ExecutionRequest request) {
        // 验证出发地
        String origin = request.getParameter("origin", String.class);
        if (origin == null || origin.trim().isEmpty()) {
            throw new IllegalArgumentException("Origin cannot be null or empty");
        }
        
        // 验证目的地
        String destination = request.getParameter("destination", String.class);
        if (destination == null || destination.trim().isEmpty()) {
            throw new IllegalArgumentException("Destination cannot be null or empty");
        }
        
        // 验证出发地和目的地不能相同
        if (origin.trim().equals(destination.trim())) {
            throw new IllegalArgumentException("Origin and destination cannot be the same");
        }
        
        // 验证乘客数量
        Integer passengerCount = request.getParameter("passengerCount", Integer.class);
        if (passengerCount != null && (passengerCount < 1 || passengerCount > 20)) {
            throw new IllegalArgumentException("Passenger count must be between 1 and 20");
        }
        
        // 验证出发时间
        LocalDateTime departureTime = request.getParameter("departureTime", LocalDateTime.class);
        if (departureTime != null && departureTime.isBefore(LocalDateTime.now())) {
            throw new IllegalArgumentException("Departure time cannot be in the past");
        }
        
        // 设置默认值
        if (!request.hasParameter("passengerCount")) {
            request.addParameter("passengerCount", 1);
        }
        
        if (!request.hasParameter("origin")) {
            request.addParameter("origin", "");
        }
        
        if (!request.hasParameter("destination")) {
            request.addParameter("destination", "");
        }
        
        if (!request.hasParameter("departureTime")) {
            request.addParameter("departureTime", LocalDateTime.now().plusDays(1));
        }
    }
    
    /**
     * 构建出行规划请求
     * 
     * @param request 执行请求
     * @return 出行规划请求
     */
    private TravelPlanRequest buildTravelPlanRequest(ExecutionRequest request) {
        return TravelPlanRequest.builder()
                .origin(request.getParameter("origin", String.class))
                .destination(request.getParameter("destination", String.class))
                .departureTime(request.getParameter("departureTime", LocalDateTime.class))
                .passengerCount(request.getParameter("passengerCount", Integer.class))
                .budgetLimit(request.getParameter("budget", Double.class))
                .userId(request.getParameter("userId", Long.class))
                .build();
    }
}